//
//  OtherTableViewController.m
//  project
//
//  Created by 张振宇 on 15/10/26.
//  Copyright © 2015年 lanou. All rights reserved.
//

#import "OtherTableViewController.h"
#import "OtherTableViewCell.h"
#import "PKRequestManager.h"
#import "OtherTableViewModel.h"
#import "StrategyDetailsViewController.h"
#import "MJRefresh.h"
#import "FMDB.h"
@interface OtherTableViewController ()
{
    BOOL isheaderreload;
}
@property (nonatomic, strong) FMDatabase *dataBase;
@property (nonatomic, strong) NSMutableArray *datasourceArr;
@property (nonatomic, strong) NSString *next_url;
@end

@implementation OtherTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
         _datasourceArr = [NSMutableArray arrayWithCapacity:0];
    isheaderreload = NO;
    [self requestData];
//    [self configureData];
    //self.tableView.bounces = NO;
//    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        [self configureData];
//    }];
    
    //刷新
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(configureData)];
    NSArray *arr = @[[UIImage imageNamed:@"1.tiff"],[UIImage imageNamed:@"2.tiff"],[UIImage imageNamed:@"3.tiff"],[UIImage imageNamed:@"4.tiff"]];
    [header setImages:arr forState:MJRefreshStateRefreshing];
    header.lastUpdatedTimeLabel.hidden = YES;
    header.stateLabel.hidden = YES;
    self.tableView.header = header;
    
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        isheaderreload = YES;
        [self configureData];
    }];
    
    [self.tableView registerClass:[OtherTableViewCell class] forCellReuseIdentifier:@"OtherTableViewCell"];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)requestData
{
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"project.db"];

    
    _dataBase = [FMDatabase databaseWithPath:filePath];
    
    if ([_dataBase open])
    {
  
        [_dataBase executeUpdate:[NSString stringWithFormat:@"create table %@ (data blob)", [NSString stringWithFormat:@"table%@",_contentId]]];
    }
    else
    {
        NSLog(@"数据库打开失败");
    }
    
    FMResultSet *resultSet = [_dataBase executeQuery:[NSString stringWithFormat:@"select * from %@",[NSString stringWithFormat:@"table%@",_contentId]]];

    while ([resultSet next])
    {
        NSData *data = [resultSet dataForColumn:@"data"];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        for (NSDictionary *dic in dict[@"data"][@"items"]) {
            OtherTableViewModel *model = [[OtherTableViewModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            //NSLog(@"%@",model.cover_image_url);
            [_datasourceArr addObject:model];
        }
    }
    
    if (_datasourceArr.count != 0)
    {
        [self.tableView reloadData];
    }
    
    [self configureData];
}

- (void)configureData
{
    NSString *str = [NSString stringWithFormat:@"http://api.liwushuo.com/v2/channels/%@/items?ad=1&gender=1&generation=1&limit=20&offset=0",_contentId];
    if ( isheaderreload) {
        str = _next_url;
    }
    
    [PKRequestManager requestWithTypeP:GET urlString:str parDic:nil finish:^(NSData *data) {
       
      
        [_dataBase executeUpdate:@"%@", [NSString stringWithFormat:@"delete * from %@",[NSString stringWithFormat:@"table%@",_contentId]]];
        
          [_dataBase executeUpdate:[NSString stringWithFormat:@"insert into %@  values (?)",[NSString stringWithFormat:@"table%@",_contentId]], data];
    
        NSDictionary *dict =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];

        
        for (NSDictionary *dic in dict[@"data"][@"items"]) {
            OtherTableViewModel *model = [[OtherTableViewModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            //NSLog(@"%@",model.cover_image_url);
            [_datasourceArr addObject:model];
            
        }
        _next_url = dict[@"data"][@"paging"][@"next_url"];
        //NSLog(@"%ld",_datasourceArr.count);
        [self.tableView reloadData];
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
        isheaderreload = NO;
    } error:^(NSError *error) {
        
    }];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return _datasourceArr.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 200;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    StrategyDetailsViewController *strategDetailsVC = [[StrategyDetailsViewController alloc]init];
    strategDetailsVC.contentId = ((OtherTableViewModel *)_datasourceArr[indexPath.row]).Myid;
    strategDetailsVC.hidesBottomBarWhenPushed = YES;
    [self.navigationC pushViewController:strategDetailsVC animated:YES];
    strategDetailsVC.hidesBottomBarWhenPushed = NO;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    OtherTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OtherTableViewCell" forIndexPath:indexPath];
    cell.selectionStyle = NO;
    cell.layer.cornerRadius = 20;
    cell.layer.masksToBounds = YES;
    //cell.textLabel.text = @"dsf";
    
    cell.configure = _datasourceArr[indexPath.row];
    // Configure the cell...
    
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
